/**
 * Copyright (c) 时间, Tal.Ben 袁东昊 (ydonghao2@gmail.com).
 *
 * 版权
 */
package com.talben.soudian.fragment.viewpagerfragment;

import java.io.Serializable;
import java.lang.ref.WeakReference;

import org.apache.http.Header;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.talben.soudian.AppContext;
import com.talben.soudian.R;
import com.talben.soudian.TDevice;
import com.talben.soudian.api.SouDianAPI;
import com.talben.soudian.base.BaseFragment;
import com.talben.soudian.bean.Constants;
import com.talben.soudian.bean.User;
import com.talben.soudian.cache.CacheManager;
import com.talben.soudian.ui.ChangeUserActivity;
import com.talben.soudian.ui.EmptyLayout;
import com.talben.soudian.ui.UIHelper;
import com.talben.soudian.widget.AvatarView;

/**
 * @Title: MyInformationFragment.java
 * @Package com.talben.soudian.fragment
 * @Description: TODO(添加描述)
 * @author Tal.Ben
 * @date 2015年5月25日 下午10:16:35
 * @version v1.0
 */
public class MyInformationFragment extends BaseFragment {

	@InjectView(R.id.iv_avatar)
	AvatarView mIvAvatar;
	@InjectView(R.id.iv_gender)
    ImageView mIvGender;
	@InjectView(R.id.tv_name)
    TextView mTvName;
	@InjectView(R.id.ly_score)
	LinearLayout mLyScore;
	@InjectView(R.id.ly_coin)
	LinearLayout mLyCoin;
	@InjectView(R.id.tv_score)
	TextView mTvScore;
	@InjectView(R.id.tv_coin)
	TextView mTvCoin;
	@InjectView(R.id.error_layout)
    EmptyLayout mErrorLayout;
    @InjectView(R.id.rootview)
    LinearLayout rootView;
    @InjectView(R.id.iv_qr_code)
    ImageView mQrCode;
    @InjectView(R.id.rl_change_user_information)
    LinearLayout mLyChangeUserInformation;
    @InjectView(R.id.rl_master)
    LinearLayout mLyMaster;
    
	private User mInfo;
	
	private boolean mIsWatingLogin;
	private AsyncTask<String, Void, User> mCacheTask;
	
	public final static String MY_INFORMATION_USER = "MyInformationFragment";
	
	@Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_information,
                container, false);
        ButterKnife.inject(this, view);
        initView(view);
        return view;
    }
	
	@Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        requestData(true);
        mInfo = AppContext.getInstance().getLoginUser();
        fillUI();
    }
	
	@Override
	public void initView(View view) {
		mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
		mIvAvatar.setOnClickListener(this);
        mErrorLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppContext.getInstance().isLogin()) {
                    requestData(true);
                } else {
                    UIHelper.gotoLoginPage(getActivity());
                }
            }
        });
        mIvAvatar.setOnClickListener(this);
        mLyScore.setOnClickListener(this);
        mLyCoin.setOnClickListener(this);
        mTvScore.setOnClickListener(this);
        mTvCoin.setOnClickListener(this);
        mQrCode.setOnClickListener(this);
        mLyChangeUserInformation.setOnClickListener(this);
        mLyMaster.setVisibility(View.GONE);
        mLyMaster.setOnClickListener(this);
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter filter = new IntentFilter(Constants.INTENT_ACTION_LOGOUT);
        filter.addAction(Constants.INTENT_ACTION_USER_CHANGE);
    }
	
	private void requestData(boolean refresh) {
        if (AppContext.getInstance().isLogin()) {
            mIsWatingLogin = false;
            String key = getCacheKey();
            if (refresh || TDevice.isNetworkReady(getActivity())
                    && (!CacheManager.isExistDataCache(getActivity(), key))) {
                sendRequestData();
            } else {
                readCacheData(key);
            }
        } else {
            mIsWatingLogin = true;
        }
    }
	
    private void readCacheData(String key) {
        cancelReadCacheTask();
        mCacheTask = new CacheTask(getActivity()).execute(key);
    }
    
    private void cancelReadCacheTask() {
        if (mCacheTask != null) {
            mCacheTask.cancel(true);
            mCacheTask = null;
        }
    }
	
	private void fillUI() {
        if (mInfo == null)
            return;
//        mIvAvatar.setAvatarUrl(mInfo.getPortrait());
        if (mInfo.getUname() != null && !mInfo.getUname().equals("")) {
        	mTvName.setText(mInfo.getUname());
		} else {
			mTvName.setText(R.string.login_or_register);
		}
//        mIvGender.setImageResource(StringUtils.toInt(mInfo.getGender()) != 2 ? R.drawable.userinfo_icon_male
//                        : R.drawable.userinfo_icon_female);
        if (mInfo.getuScore() != null && !mInfo.getuScore().equals("")) {
        	mTvScore.setText(mInfo.getuScore());
		} else {
			mTvScore.setText("0");
		}
        if (mInfo.getuCoin() != null && !mInfo.getuCoin().equals("")) {
        	mTvCoin.setText(String.valueOf(mInfo.getuCoin()));
		} else {
			mTvCoin.setText("0");
		}
//        mTvFollower.setText(String.valueOf(mInfo.getFollower()));
//        mTvFollowing.setText(String.valueOf(mInfo.getFollowing()));
    }
	
	private void sendRequestData() {
        String uid = AppContext.getInstance().getLoginUid();
        SouDianAPI.getMyInformation(uid, mHandler);
    }
	
	private final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
            try {
            	//获取用户信息
            	String result = new String(arg2,"utf-8");
                JSONObject resJObj = new JSONObject(result);
                if (resJObj.getString("result").equals("success")) {
                	mInfo.setuEmail(resJObj.getString("email"));
                    mInfo.setUname(resJObj.getString("name"));
                    mInfo.setuPhone(resJObj.getString("phone"));
                    mInfo.setuScore(resJObj.getString("score"));
                    mInfo.setuCoin(resJObj.getString("gold"));
                    mInfo.setuGiftLog(resJObj.getString("giftLog"));
                    if (mInfo != null) {
                        fillUI();
                        AppContext.getInstance().updateUserInfo(mInfo);
                        new SaveCacheTask(getActivity(), mInfo, getCacheKey())
                                .execute();
                    } else {
                        onFailure(arg0, arg1, arg2, new Throwable());
                    }
				} else {
					AppContext.showToast(resJObj.getString("msg"));
				}
                
            } catch (Exception e) {
                e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
            }
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2,
                Throwable arg3) {}
    };
	
    private String getCacheKey() {
        return "my_information" + AppContext.getInstance().getLoginUid();
    }
    
    private class CacheTask extends AsyncTask<String, Void, User> {
        private final WeakReference<Context> mContext;

        private CacheTask(Context context) {
            mContext = new WeakReference<Context>(context);
        }

        @Override
        protected User doInBackground(String... params) {
            Serializable seri = CacheManager.readObject(mContext.get(),
                    params[0]);
            if (seri == null) {
                return null;
            } else {
                return (User) seri;
            }
        }

        @Override
        protected void onPostExecute(User info) {
            super.onPostExecute(info);
            if (info != null) {
                mInfo = info;
                fillUI();
            }
        }
    }

    private class SaveCacheTask extends AsyncTask<Void, Void, Void> {
        private final WeakReference<Context> mContext;
        private final Serializable seri;
        private final String key;

        private SaveCacheTask(Context context, Serializable seri, String key) {
            mContext = new WeakReference<Context>(context);
            this.seri = seri;
            this.key = key;
        }

        @Override
        protected Void doInBackground(Void... params) {
            CacheManager.saveObject(mContext.get(), seri, key);
            return null;
        }
    }
    
    @Override
    public void onClick(View v) {
        if (!AppContext.getInstance().isLogin()) {
            AppContext.showToast(R.string.unlogin);
            UIHelper.gotoLoginPage(getActivity());
            return;
        }
        final int id = v.getId();
        switch (id) {
        case R.id.iv_avatar:
//            UIHelper.showSimpleBack(getActivity(),
//                    SimpleBackPage.MY_INFORMATION_DETAIL);
            break;
        case R.id.iv_qr_code:
//            showMyQrCode();
            break;
        case R.id.ly_score:
            UIHelper.gotoScorePage(getActivity());
            break;
        case R.id.ly_coin:
            UIHelper.gotoCoinPage(getActivity());
            break;
        case R.id.rl_change_user_information:
        	Intent intent = new Intent();
        	intent.setClass(getActivity(), ChangeUserActivity.class);
        	Bundle bundle = new Bundle();
        	bundle.putSerializable(MY_INFORMATION_USER, mInfo);
        	intent.putExtras(bundle);
        	startActivity(intent);
            break;
        case R.id.rl_master:
            UIHelper.gotoMasterPage(getActivity());
            break;
        default:
            break;
        }
    }
}

